import { Navigate, useLocation, Outlet } from 'react-router'
import useMainStore from '@/store'
import { ROUTE_WHITE_LIST } from './type'


/**
 * 路由守卫
 * 1. 未登录用户访问需要登录的页面，跳转到登录页
 * 2. 已登录用户访问登录/注册页，跳转到首页
 */
const AuthGuard = () => {
    const { pathname } = useLocation()
    const { token } = useMainStore()
    const whileList = Object.values(ROUTE_WHITE_LIST)
    // 需要登录但未登录
    if (!token && !whileList.includes(pathname)) {
        return <Navigate to="/login" replace />
    }


    // 已登录用户访问登录/注册页，跳转到首页
    if (token && whileList.indexOf(pathname) !== -1) {
        return <Navigate to="/" replace />
    }

    return <Outlet />
}

export default AuthGuard